﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Text;
using System.Net;
using System.Configuration;
using System.Data.SqlClient;

public partial class ForgotPassword : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSendMail_Click(object sender, EventArgs e)
    {
        try
        {
            string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
            SqlConnection conn = new SqlConnection(connStr);
            conn.Open();
            string sql = "Select Email, Password From Diary Where Username = @1";
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = sql;
            cmd.Parameters.AddWithValue("@1", txtUsername.Text);
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.HasRows)
            {
                reader.Read();
                string email = reader.GetString(0);
                string password = reader.GetString(1);
                SendMail(email, txtUsername.Text, password);
                reader.Close();
            }
            else
            {
                CustomValidator1.ErrorMessage = "Username invalid";
                CustomValidator1.IsValid = false;
            }
            cmd.Dispose();
            conn.Close();
        }
        catch (Exception ex)
        {
            CustomValidator1.ErrorMessage = ex.Message;
            CustomValidator1.IsValid = false;
        }
    }    

    private void SendMail(string email, string username, string password)
    {
        try
        {
            MailAddress from = new MailAddress("support@diaryonline.com");
            MailAddress to = new MailAddress(email);
            MailMessage message = new MailMessage(from, to);
            message.Subject = "Khoi phuc mat khau";
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("Chao {0}, DiaryOnline gui lai mat khau cho ban.\n", username);
            builder.AppendFormat("Mat khau cua ban: {0}", password);
            message.Body = builder.ToString();
            SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
            smtpClient.Credentials = new NetworkCredential("C1101LV@gmail.com", "123456789");
            smtpClient.Send(message);
            CustomValidator1.IsValid = false;
            CustomValidator1.ErrorMessage = "Send Mail Successfull";
        }
        catch (Exception)
        {
            CustomValidator1.IsValid = false;
            CustomValidator1.ErrorMessage = "Send Mail Fail";
        }
    }
}
